﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Shop.Logic
{
    public partial class View : Form
    {
        public View()
        {
            InitializeComponent();
        }

        private void View_FormClosing(object sender, FormClosingEventArgs e)
        {
            List<Object> temp = new List<Object>();
            temp.Add("Close");
            Shop.Program.DataIO.ToForm1(temp);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List<Object> temp = new List<Object>();
            temp.Add("Out");
            Shop.Program.DataIO.ToForm1(temp);
            this.Hide();
        }

        private void tabPage1_Enter(object sender, EventArgs e)
        {
            List<Object> temp = new List<Object>();
            temp.Add("Select");
            temp.Add("Select s.idSell as IDs, sr.surname as Продавец, s.date_Sell as Дата_продажи, s.sum as Сумма from Sell s join seller sr on (s.idseller=sr.idseller)");
            temp.Add(MainContainer);
            Shop.Program.DataIO.ToView(temp);

            temp = new List<object>();
            temp.Add("Select");
            temp.Add("select Surname as Фамилия, Name Имя, Phone Телефон from seller");
            temp.Add(UserInf);
            Shop.Program.DataIO.ToView(temp);
        }

        void UpdateDeliverPage()
        {
            String Tablename = SelectTable.Text;
            List<Object> temp = new List<object>();
            temp.Add("Select");
            switch (Tablename)
            {
                case "Поставки":
                    temp.Add("select  iddelivery,  s.Surname, datedeliver, counts , cost from Delivery d join Seller s on d.idSeller = s.idSeller");
                    break;
                case "Поставщики":
                    temp.Add("select * from vendor");
                    break;
                case "Склады":
                    temp.Add("select * from warehouse");
                    break;
                default:
                    temp.Add("select  iddelivery,  s.Surname, datedeliver, counts , cost from Delivery d join Seller s on d.idSeller = s.idSeller");
                    break;
            }

            temp.Add(DeliverView);
            Shop.Program.DataIO.ToView(temp);
        }
        private void tabPage2_Enter(object sender, EventArgs e)
        {
            UpdateDeliverPage();
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            if ((NameVendor.Text.Trim() != "") || (AdressVendor.Text.Trim() != "") || (FaxVendor.Text.Trim() != ""))
            {
                List<Object> temp = new List<object>();
                temp.Add("Insert");
                temp.Add("insert into vendor values (vendor_seq.nextval,'" + NameVendor.Text.Trim() + "','" + AdressVendor.Text.Trim() + "','" + FaxVendor.Text.Trim() + "')");
                temp.Add(returnview);
                Shop.Program.DataIO.ToView(temp);
            }
            else
            {
                returnview.Text = "Заполните все поля (null - для пустого значения)";
            }
            NameVendor.Clear();
            AdressVendor.Clear();
            FaxVendor.Clear();
            UpdateDeliverPage();
        }

        private void InsertButtonWareHouse_Click(object sender, EventArgs e)
        {
            if ((NameWarehouse.Text.Trim() != "") && (typeWareHouse.Text.Trim() != ""))
            {
                List<Object> temp = new List<object>();
                temp.Add("Insert");
                temp.Add("insert into warehouse values (warehouse_seq.nextval, '"+NameWarehouse.Text.Trim()+"','"+typeWareHouse.Text.Trim()+"')");
                temp.Add(labelviewWarehouse);
                Shop.Program.DataIO.ToView(temp);
            } else 
            {
                labelviewWarehouse.Text = "Заполните все поля (null - для пустого значения)";
            }

            NameWarehouse.Clear();
            typeWareHouse.Clear();
            UpdateDeliverPage();
        }

        private void SelectTable_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateDeliverPage();
            ViewTableNameP4.Text = SelectTable.Text;
        }

        void updaTovarPage()
        {
            vendortovar.Items.Clear();
            namesklad.Items.Clear();
            List<object>  temp = new List<object>();
            temp.Add("Select");
            temp.Add("select t.idtovar as Номер, t.name_tovar as Название, t.cost as Цена, t.period as Гарантия, t.procent_Seller as Процент, v.name_vendor as Поставщик,d.name_delivery as Доставка from tovar t left outer join delivery d on t.iddelivery = d.iddelivery left outer join vendor v on t.idvendor=v.idvendor");
            temp.Add(tovarView);
            Shop.Program.DataIO.ToView(temp);
            temp = new List<object>();
            // combobox Vendor
            temp.Add("Select List");
            temp.Add("select name_vendor from vendor");
            temp.Add(vendortovar);
            Shop.Program.DataIO.ToView(temp);
            temp = new List<object>();
            temp.Add("Select List");
            temp.Add("select name_warhouse from warehouse");
            temp.Add(namesklad);
            Shop.Program.DataIO.ToView(temp);
        }

        private void tabPage4_Enter(object sender, EventArgs e)
        {
            
            updaTovarPage();
            //обновить ComboBox
        }

        private void AcceptOnsertTovar_Click(object sender, EventArgs e)
        {
            if ((nameTovar.Text.Trim() != "") && (cost_tovar.Text.Trim() != "") &&
                    (periodtovar.Text.Trim() != "") && (periodtovar.Value > DateTime.Now) &&
                            (delivery.Text.Trim() != ""))
            {
                List<object> temp;
                // создание поставки
                if (!DAO.isexists("select * from delivery where NAME_DELIVERY = '" + delivery.Text.Trim() + "'"))
                {
                    temp = new List<object>();
                    temp.Add("Insert");
                    temp.Add("insert into delivery values (delivery_seq.nextval, (select idSeller from Seller where surname='" + login.Text.Trim() + "'), (select idwarehouse from warehouse where name_warhouse = '" + namesklad.Text.Trim() + "'), '" + delivery.Text + "',  sysdate, 0,0,(select idVendor from vendor where name_vendor='" + vendortovar.Text.Trim() + "'))");
                    temp.Add(state);
                    Shop.Program.DataIO.ToView(temp);
                    InsertTovar();
                    Update("update delivery set counts = " + 1 + ", cost = " + cost_tovar.Text.Trim() + " where NAME_DELIVERY='" + delivery.Text.Trim() + "'");
                }
                else
                {
                    //count lines      
                    InsertTovar();
                    int count = DAO.Scalar("select count(*) from tovar t where t.iddelivery = (select d.iddelivery from delivery d where d.name_delivery = '" + delivery.Text.Trim() + "')");
                    int sum = DAO.Scalar("select sum(t.cost) from tovar t where t.iddelivery = (select d.iddelivery from delivery d where d.name_delivery = '" + delivery.Text.Trim() + "')");
                    Update("update delivery set counts = " + count + ", cost = " + sum + " where NAME_DELIVERY='" + delivery.Text.Trim() + "'");
                }


                nameTovar.Clear();
                cost_tovar.Clear();
                procenttovar.Clear();
                if (isClear.Checked)
                {
                    delivery.Clear();
                }
            }
            else
            {
                MessageBox.Show("Данные введены некорректно!");
            }

            updaTovarPage();
            UpdateDeliverPage();
            
        }

        void InsertTovar()
        {
            List<object> temp = new List<object>();
            temp.Add("Insert");
            DateTime dt = (DateTime)periodtovar.Value;
            temp.Add("insert into tovar values (tovar_seq.nextval,'" + nameTovar.Text.Trim() + "'," + cost_tovar.Text.Trim() + ", to_date('" + dt + "','dd.mm.yyyy HH24:mi:ss') ," + procenttovar.Text.Trim() + ",(select idvendor from vendor where name_vendor = '" + vendortovar.Text + "'),(select iddelivery from delivery where name_delivery = '" + delivery.Text.Trim() + "'))");
            temp.Add(state);
            Shop.Program.DataIO.ToView(temp);
        }

        void Update(String cmd)
        {
            List<object> temp = new List<object>();
            temp.Add("Update");
            temp.Add(cmd);
            temp.Add(state);
            Shop.Program.DataIO.ToView(temp);
        }

        private void Clear_Click(object sender, EventArgs e)
        {
            ClearBox();
        }

        void ClearBox()
        {
            nameTovar.Clear();
            cost_tovar.Clear();
            procenttovar.Clear();
            if (isClear.Checked)
            {
                delivery.Clear();
            }
        }

        private void DeliverView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            viewSelectedDeliver.Text = DeliverView[0, DeliverView.CurrentRow.Index].Value.ToString();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                int index = Convert.ToInt32(DeliverView[0, DeliverView.CurrentRow.Index].Value.ToString());
                List<object> temp = new List<object>();
                temp.Add("Delete");
                switch (SelectTable.Text)
                {
                    case "Поставки":
                        temp.Add("DELETE from delivery where iddelivery = " + index);
                        break;
                    case "Склады":
                        temp.Add("DELETE from warehouse where idwarehouse = " + index);
                        break;
                    case "Поставщики":
                        temp.Add("DELETE from vendor where idvendor = " + index);
                        break;
                }
                temp.Add(viewSelectedDeliver);
                Shop.Program.DataIO.ToView(temp);
                UpdateDeliverPage();
            } catch (Exception ex)
            {
                viewSelectedDeliver.Text = ex.Message;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {

            try
            {
                int index = Convert.ToInt32(tovarView[0, tovarView.CurrentRow.Index].Value.ToString());
                List<object> temp = new List<object>();
                temp.Add("Delete");
                temp.Add("DELETE from tovar where idtovar = " + index);
                temp.Add(tovarState);
                Shop.Program.DataIO.ToView(temp);
                updaTovarPage();
            }
            catch (Exception ex)
            {
                tovarState.Text = ex.Message;
            }

        }

        private void tabPage5_Enter(object sender, EventArgs e)
        {
            UpdateUserPage();
        }

        void UpdateUserPage()
        {
            List<object> temp = new List<object>();
            temp.Add("Select");
            temp.Add("Select idseller as ID,name as Имя, surname as Фамилия, phone as Телефон, birth_date as ДатаРОждения, adress as Адрес, Date_invite as Зачислен from seller");
            //temp.Add("Select * from seller");
            temp.Add(UserViewPage);
            Shop.Program.DataIO.ToView(temp);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if ((nameUser.Text.Trim() != "") && (surnameUser.Text.Trim() != "") && (birthUser.Value < DateTime.Now)
                    && (passUser.Text.Trim() != "") && (fatherNameUser.Text.Trim() != "") && (AdressUser.Text.Trim() != "")
                        && (phoneUser.Text.Trim() != ""))
            {
                InsertUser();
            }
        }

        void InsertUser()
        {
            List<object> temp = new List<object>();
            temp.Add("Insert");
            temp.Add("INSERT INTO SELLER VALUES (seller_seq.nextval,'"+nameUser.Text.Trim()+"','"+surnameUser.Text.Trim()+"','"+fatherNameUser.Text.Trim()+"',to_date('"+birthUser.Value+"','dd.mm.yyyy HH24:mi:ss'),'"+AdressUser.Text.Trim()+"','"+phoneUser.Text.Trim()+"',sysdate,'"+passUser.Text.Trim()+"')");
            temp.Add(stateUser);
            Shop.Program.DataIO.ToView(temp);
            UpdateUserPage();
        }

        private void button5_Click(object sender, EventArgs e)
        {

            try
            {
                int index = Convert.ToInt32(UserViewPage[0, UserViewPage.CurrentRow.Index].Value.ToString());
                List<object> temp = new List<object>();
                temp.Add("Delete");
                temp.Add("DELETE from Seller where idSeller = " + index);
                temp.Add(stateUser);
                Shop.Program.DataIO.ToView(temp);
                UpdateUserPage();
            }
            catch (Exception ex)
            {
                stateUser.Text = ex.Message;
            }
        }

    }
}

